﻿using System;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Collections.Generic;
using System.Windows.Forms;
using CurrencyConv.Core;

namespace CurrencyConv
{
	public partial class BoxAndCurrency : UserControl
	{
		public BoxAndCurrency()
		{
			InitializeComponent();
		}

		public void Bind(IEnumerable<Money> currencies, string selectedCurrency)
		{
			List<Money> datasource = new List<Money>(currencies);

			cboFirstDDL.DataSource = datasource;
			cboFirstDDL.DisplayMember = "CurrencyCode";
			cboFirstDDL.ValueMember = "CurrencyCode";
			cboFirstDDL.SelectedItem = datasource.FirstOrDefault(m => m.CurrencyCode == selectedCurrency);

			txtFirst.LostFocus += new EventHandler(OnTextBoxGotFocus);
			txtFirst.GotFocus += new EventHandler(OnTextBoxLostFocus);
			cboFirstDDL.SelectedIndexChanged += new EventHandler(cboFirstDDL_SelectedIndexChanged);
		}

		private void OnTextBoxLostFocus(object sender, EventArgs e)
		{
			AmmountOrCurrencyChanged(this, e);
		}

		void OnTextBoxGotFocus(object sender, EventArgs e)
		{
			AmmountOrCurrencyChanged(this, e);
			TextboxGotFocus(this, e);
		}

		void cboFirstDDL_SelectedIndexChanged(object sender, EventArgs e)
		{
			AmmountOrCurrencyChanged(this, e);
		}

		public Money Ammount
		{
			get
			{
				if (string.IsNullOrEmpty(txtFirst.Text))
					return new Money(cboFirstDDL.SelectedItem as Money, 1);

				return new Money(cboFirstDDL.SelectedItem as Money, Convert.ToDecimal(txtFirst.Text,new CultureInfo("en-US")));
			}
			set
			{
				if (value == null)
				{
					txtFirst.Text = "0";
					return;
				}
				txtFirst.Text = value.Ammount.ToString();
			}
		}

		public Money SelectedCurrency
		{
			get
			{
				return cboFirstDDL.SelectedItem as Money;
			}
		}

		public event EventHandler AmmountOrCurrencyChanged = delegate { };
		public event EventHandler TextboxGotFocus = delegate { };
	}
}
